import React, { Component } from 'react'
import './list.css'
import PubSub from 'pubsub-js'

export default class List extends Component {
  state = {
    // 初始化状态
    users: [],
    // 第一次打开页面
    isFirst: true,
    // 是否加载
    isLoading: false,
    // 存储请求相关错误信息
    err: '',
  }

  // 开启订阅
  componentDidMount() {
    this.token = PubSub.subscribe('Jetwang', (_, data) => {
      this.setState(data)
    })
  }

  // 取消订阅
  componentWillUnmount() {
    PubSub.unsubscribe(this.token)
  }

  render() {
    const { users, isFirst, isLoading, err } = this.state
    return (
      <div className="list">
        {isFirst ? (
          <h3>欢迎使用，请输入关键字，然后点击搜索</h3>
        ) : isLoading ? (
          <h3>Loading......</h3>
        ) : err ? (
          <h3 style={{ color: 'red' }}>{err}</h3>
        ) : (
          users.map(item => {
            return (
              <div className="card" key={item.id}>
                <a href={item.html_url}>
                  <img src={item.avatar_url} alt="" />
                </a>
                <p>{item.login}</p>
              </div>
            )
          })
        )}
      </div>
    )
  }
}
